﻿using System;
//using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Google.GData.Client;
using Google.GData.Calendar;
using Google.GData.Extensions;
using Microsoft.WindowsMobile.PocketOutlook;

namespace Synchro
{
    public partial class Synchro : Form
    {
        Credentials _credentials;
        Google _google;
        Outlook _outlook;

        public Synchro(Credentials credentials)
        {
            _credentials = credentials;
            _outlook = new Outlook();
            InitializeComponent();
        }

        private void botUser_Click(object sender, EventArgs e)
        {
            labelInfoConn.Text = "Verifying credentials...";

            string user = textUser.Text;
            string password = textPassword.Text;

            _credentials.User = user;
            _credentials.Password = password;

            _google = new Google(_credentials);

            /* Código para obtener todos los calendarios
             * y ponerlos en el ComboBox de la siguiente
             * pestaña */
            try
            {
                ArrayList calendars = _google.updateCalendars();
                if (calendars != null)
                {
                    comboCalendar.Items.Clear();
                    for (int i = 0; i < calendars.Count; i++)
                    {
                        comboCalendar.Items.Add(calendars[i]);
                    }
                    comboCalendar.SelectedIndex = 0;
                    labelInfoConn.Text = "Credentials have been succesfully veryfied";
                } 
                else 
                {
                    labelInfoConn.Text = "No Calendars available";
                }
            }
            catch (AuthenticationException exc)
            {
                labelInfoConn.Text = "Credentials are not correct";
            }

        }

        public void fromGoogleToOutlook()
        {
            if ((_google != null) && (_google.isConnected()))
            {
                label4.Text = "";
                
                EventFeed google_events = _google.getAllEntries(comboCalendar.SelectedIndex);
                AppointmentCollection outlook_events = _outlook.getAppointments();
                for (int i = 0; i < google_events.Entries.Count; i++)
                {
                    EventEntry google_entry = (EventEntry)google_events.Entries[i];
                    
                    if (!google_entry.Times[0].AllDay)
                    {
                        Console.WriteLine("Todo el día");
                        google_entry.Times[0].StartTime = google_entry.Times[0].StartTime.AddHours(1);
                        google_entry.Times[0].EndTime = google_entry.Times[0].EndTime.AddHours(1);
                    }
                    if (!appointmentExistsInOutlook(google_entry, outlook_events))
                    {
                        if (_outlook.addAppointment(google_entry.Title.Text, google_entry.Times[0].StartTime, google_entry.Times[0].EndTime))
                        {
                            label4.Text += "Se añade: " + google_entry.Title.Text + "\n";
                        }
                        else
                        {
                            label4.Text += "No se ha añadido: " + google_entry.Title.Text + "\n";
                        }
                    }
                    else
                    {
                        label4.Text += "No se ha añadido: " + google_entry.Title.Text + "\n";
                    }
                }
                label4.Text += "\nAppointments have been synchronized\n";
            }
            else
            {
                label4.Text = "You have not been logged yet";
            }
        }

        public void fromOutlookToGoogle()
        {
            AppointmentCollection outlook_events = _outlook.getAppointments();
            EventFeed google_events = _google.getAllEntries(comboCalendar.SelectedIndex);
            for (int i = 0; i < outlook_events.Count; i++)
            {
                if (!appointmentExistsInGoogle(outlook_events[i], google_events))
                {
                    EventEntry entry = new EventEntry();

                    // Set the title and content of the entry.
                    entry.Title.Text = outlook_events[i].Subject;
                    //entry.Content.Content = outlook_events[i].Body;


                    // Set a location for the event.
                    //Where eventLocation = new Where();
                    //eventLocation.ValueString = "South Tennis Courts";
                    //entry.Locations.Add(eventLocation);

                    When eventTime = new When(outlook_events[i].Start.AddHours(-1), outlook_events[i].End.AddHours(-1));
                    entry.Times.Add(eventTime);

                    //Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
                    Uri postUri = new Uri(_google.CalendarUri);

                    // Send the request and receive the response:
                    //AtomEntry insertedEntry = _google.insertEntry(entry);
                    _google.insertEntry(entry);
                    label4.Text += "Se ha añadido: " + outlook_events[i].Subject + "\n";
                }
                else
                {
                    label4.Text += "No se ha añadido: " + outlook_events[i].Subject + "\n";
                }
            }
        }

        private void botSynchro_Click(object sender, EventArgs e)
        {
            _google.modifyUri(comboCalendar.SelectedIndex);
            fromGoogleToOutlook();
            fromOutlookToGoogle();
        }

        public bool appointmentExistsInOutlook(EventEntry appt_searched,AppointmentCollection appt_col)
        {
            DateTime start = appt_searched.Times[0].StartTime.AddHours(8);
            DateTime end = appt_searched.Times[0].EndTime.AddHours(8);
         
            /*if (!appt_searched.Times[0].AllDay)
            {
                start = start.AddHours(1);
                end = end.AddHours(1);
            }*/
            string title = appt_searched.Title.Text;
            Appointment appt = null;
            for (int i=0;i<appt_col.Count;i++)
            {
                appt = appt_col[i];
                if ((start.CompareTo(DateTime.Now)<=0)|| ((appt.Subject == title) && (appt.Start.CompareTo(start)==0) && (appt.End.CompareTo(end)==0)))
                {
                    return true;
                }
            }
            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label4.Text = "";
        }

        public bool appointmentExistsInGoogle(Appointment appt_searched, EventFeed appt_col)
        {
            DateTime start = appt_searched.Start.AddHours(-9);
            DateTime end = appt_searched.End.AddHours(-9);
            string title = appt_searched.Subject;
            for (int i = 0; i < appt_col.Entries.Count; i++)
            {
                EventEntry appt = (EventEntry) appt_col.Entries[i];
                if ((start.CompareTo(DateTime.Now) <= 0) || ((appt.Title.Text == title) && (appt.Times[0].StartTime.CompareTo(start) == 0) && (appt.Times[0].EndTime.CompareTo(end) == 0)))
                {
                    return true;
                }
            }
            return false;
        }
    }
}